// 系统用户信息store
import { defineStore } from 'pinia';
import { store } from '@/store';

// 引入cookie
import { ElckerCookie, ElckerTokenKey } from '~/utils/cookie';
//引入对应的API
import ElckerAuthApi from '@/api/elcker/ElckerAuthApi';

export const elckerAuthPiniaStore = defineStore({
  id: 'elckerAuthStore',
  state: () =>
    ({
      userInfo: ElckerCookie.get(ElckerTokenKey.userInfoKey)
        ? JSON.parse(ElckerCookie.get(ElckerTokenKey.userInfoKey))
        : null, // 用户信息对象
      accessToken: ElckerCookie.get(ElckerTokenKey.accessTokenKey), // 访问令牌字符串
      refreshToken: ElckerCookie.get(ElckerTokenKey.refreshTokenKey), // 刷新令牌字符串
      isLogin: ElckerCookie.get(ElckerTokenKey.isCome) ? JSON.parse(ElckerCookie.get(ElckerTokenKey.isCome)) : false,
    } as ElckerAuthStore),
  getters: {
    getUser(): ElckerUser | any {
      return this.userInfo;
    },
    getToken(): string {
      return this.accessToken;
    },
    getIsLogin(): boolean {
      return this.isLogin;
    },
    getRefreshToken(): string {
      return this.refreshToken;
    },
    getElckerState(): ElckerAuthStore {
      return this;
    },
  },
  actions: {
    // 登录操作
    UserLogin(userData: ElckerLoginUser) {
      const { username, password } = userData;
      return new Promise((resolve, reject) => {
        if (import.meta.env.VITE_USE_MOCK) {
          const response = {
            access_token: '1221212121123123123123213123', // 访问令牌，随机30个字符
            token_type: 'bearer',
            refresh_token: 'eyJ1c2VySW5mbyI6eyJtb2JpbGUiO', // 刷新令牌，随机30个字符
            expires_in: '1500', // access_token 有效时长(秒)
            scope: 'all', // 权限范围
            userInfo: {
              // 用户信息
              uid: '213', // 用户id
              username: 'ceshi',
              mobile: '12345678912',
              email: '123@qq.com',
              nickName: '测试',
              imageUrl: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            },
            jti: 'sadasdsadsadsadsadas', // token 的唯一标识
          };
          const { userInfo, access_token, refresh_token } = response;
          this.userInfo = userInfo;
          this.accessToken = access_token;
          this.refreshToken = refresh_token;
          this.isLogin = true;
          // 保存到cookie中
          ElckerCookie.set(ElckerTokenKey.userInfoKey, userInfo);
          ElckerCookie.set(ElckerTokenKey.accessTokenKey, access_token);
          ElckerCookie.set(ElckerTokenKey.refreshTokenKey, refresh_token);
          ElckerCookie.set(ElckerTokenKey.isCome, 'true');
          resolve(response); // 正常响应钩子
        } else {
          ElckerAuthApi.userLogin({ username: username.trim(), password: password })
            .then((response: any) => {
              const { userInfo, access_token, refresh_token } = response;
              this.userInfo = userInfo;
              this.accessToken = access_token;
              this.refreshToken = refresh_token;
              this.isLogin = true;
              // 保存到cookie中
              ElckerCookie.set(ElckerTokenKey.userInfoKey, userInfo);
              ElckerCookie.set(ElckerTokenKey.accessTokenKey, access_token);
              ElckerCookie.set(ElckerTokenKey.refreshTokenKey, refresh_token);
              ElckerCookie.set(ElckerTokenKey.isCome, 'true');
              resolve(response); // 正常响应钩子
            })
            .catch((error: any) => {
              // 重置状态
              this.userInfo = null;
              this.accessToken = '';
              this.refreshToken = '';
              this.isLogin = false;
              // 移除cookie中的数据
              ElckerCookie.remove(ElckerTokenKey.userInfoKey);
              ElckerCookie.remove(ElckerTokenKey.accessTokenKey);
              ElckerCookie.remove(ElckerTokenKey.refreshTokenKey);
              ElckerCookie.remove(ElckerTokenKey.isCome);
              reject(error); // 异常
            });
        }
      });
    },

    // 退出
    UserLogout(redirectURL?: string) {
      // 调用退出接口, 上面不要忘记导入 logout 方法
      ElckerAuthApi.userLoginOut(this.accessToken)
        .then(() => {
          // 重置状态
          this.userInfo = null;
          this.accessToken = '';
          this.refreshToken = '';
          this.isLogin = false;
          // 移除cookie中的数据
          ElckerCookie.remove(ElckerTokenKey.userInfoKey);
          ElckerCookie.remove(ElckerTokenKey.accessTokenKey);
          ElckerCookie.remove(ElckerTokenKey.refreshTokenKey);
          ElckerCookie.remove(ElckerTokenKey.isCome);
          // 重写向回来源地址，如果没有传重定向地址则回到到登录页
          window.location.href = (redirectURL || import.meta.env.VUE_APP_PAGE_LOGIN) + '';
        })
        .catch(() => {
          // 重置状态
          this.userInfo = null;
          this.accessToken = '';
          this.refreshToken = '';
          this.isLogin = false;
          // 移除cookie中的数据
          ElckerCookie.remove(ElckerTokenKey.userInfoKey);
          ElckerCookie.remove(ElckerTokenKey.accessTokenKey);
          ElckerCookie.remove(ElckerTokenKey.refreshTokenKey);
          ElckerCookie.remove(ElckerTokenKey.isCome);
          window.location.href = (redirectURL || import.meta.env.VUE_APP_PAGE_LOGIN) + '';
        });
    },

    // 发送刷新令牌
    SendRefreshToken({ state }: any) {
      return new Promise((resolve, reject) => {
        // 判断是否有刷新令牌
        if (!state.refreshToken) {
          this.userInfo = null;
          this.accessToken = '';
          this.refreshToken = '';
          this.isLogin = false;
          // 移除cookie中的数据
          ElckerCookie.remove(ElckerTokenKey.userInfoKey);
          ElckerCookie.remove(ElckerTokenKey.accessTokenKey);
          ElckerCookie.remove(ElckerTokenKey.refreshTokenKey);
          ElckerCookie.remove(ElckerTokenKey.isCome);
          reject('没有刷新令牌');
          return;
        }
        // 发送请求
        ElckerAuthApi.refreshToken(state.refreshToken)
          .then((response: any) => {
            // 更新用户状态新数据
            const { userInfo, access_token, refresh_token } = response;
            this.userInfo = userInfo;
            this.accessToken = access_token;
            this.refreshToken = refresh_token;
            this.isLogin = true;
            // 保存到cookie中
            ElckerCookie.set(ElckerTokenKey.userInfoKey, userInfo);
            ElckerCookie.set(ElckerTokenKey.accessTokenKey, access_token);
            ElckerCookie.set(ElckerTokenKey.refreshTokenKey, refresh_token);
            ElckerCookie.set(ElckerTokenKey.isCome, 'true');
            resolve(response); // 正常钩子
          })
          .catch((error: any) => {
            // 重置状态
            this.userInfo = null;
            this.accessToken = '';
            this.refreshToken = '';
            this.isLogin = false;
            // 移除cookie中的数据
            ElckerCookie.remove(ElckerTokenKey.userInfoKey);
            ElckerCookie.remove(ElckerTokenKey.accessTokenKey);
            ElckerCookie.remove(ElckerTokenKey.refreshTokenKey);
            ElckerCookie.remove(ElckerTokenKey.isCome);
            reject(error);
          });
      });
    },
  },
});

// Need to be used outside the setup
export function elckerAuthStoreOutside() {
  return elckerAuthPiniaStore(store);
}
